/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 *
 * @author spthanh
 */
public class Batches_PreparedStmt_Example {
    public static void main(String[] args){
         try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks", "sa", "123");

            //Turn off auto-commit
            con.setAutoCommit(false);

            //Create an instance of preparedstatement
            String query = "INSERT INTO Student(FirstName,LastName,Address,Age,Description) VALUES(?,?,?,?,?)";
            PreparedStatement pstmt = con.prepareStatement(query);

            //Set value for parameters
            pstmt.setString(1, "Nguyen");
            pstmt.setString(2, "Minh");
            pstmt.setString(3, "34/B Ly Thanh Ton");
            pstmt.setInt(4, 20);
            pstmt.setString(5 , "Normally student");

            //Add batches for preparedStatement
            pstmt.addBatch();

            pstmt.setString(1, "Hoang");
            pstmt.setString(2, "Tuan");
            pstmt.setString(3, "3E Ly Thanh Ton");
            pstmt.setInt(4, 25);
            pstmt.setString(5 , "Special student");
            pstmt.addBatch();

            //Submit the batches for execution
            int[] results = pstmt.executeBatch();
            for(int item :  results){
                System.out.println("Value :" + item);
            }

            //Commit changes into database
            con.commit();

            //Enable again for auto-commit
            con.setAutoCommit(true);


        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
   
}
